<template>
  <div class="handBase">
    <div class="warning">
      <p>
        <i>◎</i>请按照如下格式填写：
      </p>
      <div class="ege">
        <p>张三，15696969696，浙江省 杭州市 余杭区 南京路288号105室</p>
        <span>1、收件人名字、手机号、地址间用逗号隔开</span>
        <br>
        <span>2、地址省市区详细地址用一个空格分隔，如无区县信息则默认填写其他区</span>
        <br>
        <span class="import">3、请确认输入的信息与选中的平台保持一致</span>
      </div>
    </div>
    <div class="packageList" v-for="(item, index) in ordersArr" :key="index" @keyup.13="watchData(item, index)">
      <div class="topInput" v-if="shopType!=5">
        <el-input @blur="watchData(item, index)" class="orders inp" v-model="item.orderNo" placeholder="请输入订单号"></el-input>
        <el-input @blur="watchData(item, index)" class="address inp" v-model="item.allAddress" placeholder="请输入收件信息"></el-input>
        <i class="close el-icon-circle-close" v-if="ordersArr.length > 1" @click="dele(index)"></i>
        <el-button type="primary" size="mini" @click="watchData(item, index)">选礼品</el-button>
        <!-- <i class="add el-icon-circle-plus" v-if="index == (ordersArr.length-1)" @click="addArr"></i> -->
      </div>
      <div class="topOtherInput" v-if="shopType==5">
        <el-input @blur="watchData(item, index)" class="sInput" v-model="item.orderNo" placeholder="订单号"></el-input>
        <el-input @blur="watchData(item, index)" class="sInput" v-model="item.receiveName" placeholder="收件人姓名"></el-input>
        <el-input @blur="watchData(item, index)" class="sInput" v-model="item.telephone" placeholder="手机号" type="number"></el-input>
        <el-input @blur="watchData(item, index)" class="lInput" v-model="item.address" placeholder="省 市 区"></el-input>
        <i class="close el-icon-circle-close" v-if="ordersArr.length > 1" @click="dele(index)"></i>
        <el-button type="primary" size="mini" @click="watchData(item, index)">选礼品</el-button>
        <!-- <i class="add el-icon-circle-plus" v-if="index == (ordersArr.length-1)" @click="addArr"></i> -->
      </div>
      <div class="checkArea" v-if="item.isAll">
        <div class="left">
          <span>请选择礼品包</span>
        </div>
        <div class="right">
          <myPackage :isFar="isFar(item.address)" @setIdChange="setIdChange($event, index)" @replacePackage="replacePackage" :index="replacePackageIndex"></myPackage>
        </div>
      </div>
      <div class="addOthers">
        <i class="add el-icon-circle-plus" v-if="index == (ordersArr.length-1)" @click="addArr"></i>
      </div>
    </div>
    <div class="total">
      <p class="common">
        备注：我们统一使用
        <strong>圆通</strong>
        快递发货
      </p>
      <p class="totalPrice">
        总价：
        <em>{{ payTotal }}元</em>
      </p>
    </div>
    <div class="footer">
      <b class="button-n" @click="toPay">确认支付</b>
    </div>
    <NoMoney v-if="errorType==1" :money="leftMoney" @closeNoMoney="closeNoMoney"></NoMoney>
  </div>
</template>
<script type="text/ecmascript-6">
import MyPackage from '../../../base/myPackage/index'
import { mapGetters, mapActions } from 'vuex'
import NoMoney from '../../../base/alert/noMoney'
export default {
  name: 'handBase',
  components: {
    MyPackage,
    NoMoney
  },
  props: {
    shopType: {
      type: Number
    }
  },
  data () {
    return {
      ordersArr: [{
        orderNo: '',
        allAddress: '',
        receiveName: '',
        address: '',
        setId: '',
        money: 0,
        telephone: '',
        isAll: false,
        commonList: [], // 常用礼品包
        priceObj: {}
      }],
      errorType: -1,
      leftMoney: 0
    }
  },
  computed: {
    payTotal: {
      get: function () {
        let arr = this.ordersArr
        let total = 0
        for (let i = 0; i < arr.length; i++) {
          total = total + arr[i].money
        }
        return total.toFixed(2)
      },
      set: function (val) {
        return val
      }
    },
    ...mapGetters([
      'userInfo',
      'sellerInfo'
    ])
  },
  methods: {
    isFar (address) {
      let bol = false
      let arr = ['新疆', '西藏', '内蒙古', '甘肃', '青海', '宁夏', '海南']
      for (let i = 0; i < arr.length; i++) {
        if (address.indexOf(arr[i]) > -1) {
          bol = true
        }
      }
      if (bol) {
        return {
          farNum: 1,
          normalNum: 0
        }
      } else {
        return {
          farNum: 0,
          normalNum: 1
        }
      }
    },
    addArr () { // 添加按钮新增一条订单
      this.ordersArr.push({
        orderNo: '',
        allAddress: '',
        receiveName: '',
        address: '',
        setId: '',
        money: 0,
        telephone: '',
        isAll: false
      })
    },
    dele (index) { // 删除
      this.ordersArr.splice(index, 1)
    },
    watchData (item, index) { // 检测信息输入完整显示礼品包信息
      if (this.shopType === 5) { // 手工下单其他店铺类型
        if (item.orderNo !== '' && item.receiveName !== '' && item.telephone !== '' && item.address !== '') {
          this.ordersArr[index].isAll = true
        } else if (item.orderNo === '') {
          this.$message({
            message: '请输入订单号',
            type: 'warning'
          })
        } else if (item.receiveName === '') {
          this.$message({
            message: '请输入收件姓名',
            type: 'warning'
          })
        } else if (item.telephone === '') {
          this.$message({
            message: '请输入手机号码',
            type: 'warning'
          })
        } else if (item.address === '') {
          this.$message({
            message: '请输入地址',
            type: 'warning'
          })
        }
      } else { // 常见的店铺时
        if (item.orderNo !== '' && item.allAddress !== '') {
          this.ordersArr[index].isAll = true
          let allAddress = item.allAddress.replace(/,/g, '&&address&&')
          allAddress = allAddress.replace(/，/g, '&&address&&')
          let arr = allAddress.split('&&address&&')
          if (arr.length !== 3) {
            this.$message({
              message: `收件信息输入不完整`,
              type: 'error'
            })
          } else {
            this.ordersArr[index].receiveName = arr[0]
            this.ordersArr[index].telephone = arr[1]
            this.ordersArr[index].address = arr[2]
          }
        } else if (item.orderNo === '') {
          this.$message({
            message: '请输入订单号',
            type: 'warning'
          })
        } else if (item.allAddress === '') {
          this.$message({
            message: '请输入收件信息',
            type: 'warning'
          })
        }
      }
    },
    setIdChange (arr, index) { // arr [ setId, money ]
      this.ordersArr[index].setId = arr[0]
      this.ordersArr[index].money = arr[1]
    },
    toPay () { // 支付之前的校验
      let telReg = /^[1][0-9]{10}$/
      let addressReg = /(^(([\u4e00-\u9fa5]+)([\s]+)){3}([\u4e00-\u9fa5]+))/
      let orderIdReg = /^[(0-9)-]+$/
      let arr = this.ordersArr
      let bol = false
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].orderNo === '') {
          this.$message({
            message: `第${i + 1}条请输入订单号`,
            type: 'error'
          })
          bol = false
          return false
        } else if (arr[i].receiveName === '') {
          this.$message({
            message: `第${i + 1}条请输入收件人姓名`,
            type: 'error'
          })
          bol = false
          return false
        } else if (!telReg.test(arr[i].telephone)) {
          this.$message({
            message: `第${i + 1}条手机格式有误`,
            type: 'error'
          })
          bol = false
          return false
        } else if (!addressReg.test(arr[i].address)) {
          this.$message({
            message: `第${i + 1}条地址格式输入有误`,
            type: 'error'
          })
          bol = false
          return false
        } else if (!orderIdReg.test(arr[i].orderNo)) {
          this.$message({
            message: `第${i + 1}条订单号格式输入有误`,
            type: 'error'
          })
          bol = false
          return false
        } else if (arr[i].setId === '') {
          this.$message({
            message: `第${i + 1}条请选择礼品包`,
            type: 'error'
          })
          bol = false
          return false
        } else {
          bol = true
        }
      }
      if (bol === true) {
        this.creatOrderPost()
      }
    },
    creatOrderPost () { // 验证通过, 生成订单
      this.$ajax.post('/file/task/upload/uploadHand', {
        sellerAccountId: this.userInfo.sellerAccountId,
        shopType: this.shopType,
        logisticsType: '1',
        orders: this.ordersArr
      }).then((data) => {
        if (data.data.code === '200') {
          let res = data.data.data
          if (res.code === -1) {
            this.$alert('"' + res.productName + '"' + res.msg + '请重新选择商品', '提示', {
              confirmButtonText: '确定',
              callback: action => {
              }
            })
          } else {
            this.setHandTable(res)
            if (res.realNum === res.totalNum) {
              this.sureToPayPost(res.orderId)
            } else {
              this.$message({
                message: '订单生成失败, 请检查填写的信息是否有误',
                type: 'error'
              })
            }
          }
        } else {
          this.$message({
            message: data.data.message,
            type: 'error'
          })
        }
      }).catch((err) => {
        console.error(err)
        this.$message({
          message: '生意太火爆了, 请稍后再试',
          type: 'error'
        })
      })
    },
    sureToPayPost (orderId) { // 验证格式什么的通过, 订单生成成功, 请求支付接口
      if (this.sellerInfo.balance - this.payTotal < 0) {
        this.leftMoney = (this.payTotal - this.sellerInfo.balance).toFixed(2)
        this.errorType = 1
      } else {
        this.$confirm('确认支付该订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.post('/api/order/operate/pay', {
            orderId: orderId
          }).then((data) => {
            if (data.data.code === '200') {
              if (data.data.data.code === 0) {
                this.$message({
                  message: '支付成功',
                  type: 'success'
                })
                this.$router.push({ name: 'paySuccess', query: { orderId: orderId } })
              } else if (data.data.data.code === -1) {
                this.$alert('"' + data.data.data.productName + '"' + data.data.data.msg + '请撤销订单后选择其他商品重新下单', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$router.push({ name: 'orderManger' })
                  }
                })
              } else {
                this.$message({
                  message: data.data.data.msg,
                  type: 'error'
                })
              }
            } else {
              this.$message({
                message: data.data.message,
                type: 'error'
              })
            }
          }).catch((err) => {
            console.error(err)
            this.$message({
              message: '生意太火爆了, 请稍后再试',
              type: 'error'
            })
          })
        })
      }
    },
    closeNoMoney () { // 关闭余额不足弹框
      this.errorType = -1
      this.$router.push({ name: 'orderManger' })
    },
    ...mapActions([
      'setHandTable',
      'setCommonPackage'
    ])
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../../assets/stylus/index.styl'
.handBase
  .warning
    display flex
    p
      fontSize($fontSize-m, 30px, $fontColor)
      i
        margin-right 20px
    span
      fontSize($fontSize, 20px, $fontColor-gray)
    .import
      color $mainColor
  .packageList
    margin-top 40px
    .addOthers
      margin-bottom 12px
      margin-top 12px
    .close
      fontSize(26px, 1, $fontColor-o)
      cursor pointer
      vertical-align middle
    .add
      fontSize(26px, 1, $textBtnColor)
      cursor pointer
      vertical-align middle
    .topInput
      margin-bottom 16px
      .inp
        margin-bottom 10px
      .orders
        width 164px
        // margin-right 20px
      .address
        width 460px
        margin-right 26px
    .topOtherInput
      margin-bottom 16px
      .sInput
        width 120px
        margin-bottom 10px
        // margin-right 20px
      .lInput
        width 240px
        margin-right 26px
    .checkArea
      border 1px solid #dddddd
      display flex
      .left
        width 150px
        text-align center
        display flex
        flex-direction column
        justify-content center
        background #F6F6F6
        fontSize($fontSize, 1, $fontColor)
      .right
        padding 30px
  .total
    margin-top 24px
    height 53px
    line-height 53px
    padding 0 20px
    background #EEEEEE
    display flex
    justify-content space-between
    align-items center
    .common
      fontSize($fontSize-s, 1, $fontColor-gray)
      strong
        color $fontColor-o
    .totalPrice
      fontSize(24px, 1, $fontColor)
      em
        color $mainColor
  .footer
    margin-top 40px
    text-align center
.replacePackage
  position fixed
  z-index 13
  top 0
  left 0
  width 100%
  height 100%
  background rgba(0, 0, 0, 0.6)
  overflow auto
  .replaceWrap
    position absolute
    text-align center
    top 20vh
    width 600px
    background #ffffff
    padding 30px 40px
    left 0
    right 0
    margin 0 auto
    h2
      font-size 18px
      font-weight bold
      line-height 30px
      margin-bottom 20px
    .footer
      text-align center
      margin-top 40px
</style>
